import logging
import os
import string
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from models import AppUser, Bookmark

class GoHandler(webapp.RequestHandler):
	def get(self):
		path = str(self.request.path)[1:]
		path = path.lstrip('/')
		path = path.rstrip('/')

		if not users.get_current_user():
			self.redirect(users.create_login_url('/x'))
			return

		query = AppUser.all().filter('user =', users.get_current_user())
		try:
			app_user = query.fetch(1)[0]
		except:
			# logged in, no app_user
			self.redirect("/add_user")
			return

		bookmarks = Bookmark.all().filter('app_user', app_user)

		if not '/' in path:
			path = os.path.join(os.path.dirname(__file__), 'view_me.html')
			data = {'app_user':app_user, 'bookmarks': bookmarks}
			self.response.out.write(template.render(path, data))
			return
		else:
			name = '/'.join(path.split('/')[1:])
			
			query = Bookmark.all().filter('name =', name).filter('app_user =', app_user)
			
			try:
				bookmark = query.fetch(1)[0]
			except:
				path = os.path.join(os.path.dirname(__file__), 'view_me.html')
				data = {'messages': ['You do not have a bookmark with that name'], 'app_user':app_user, 'bookmarks':bookmarks}
				self.response.out.write(template.render(path, data))
				return
			
			bookmark.hits += 1
			bookmark.put()
			self.redirect(bookmark.url)
		
def main():
	app = webapp.WSGIApplication([(r'.*', GoHandler)], debug=True)
	wsgiref.handlers.CGIHandler().run(app)
	
if __name__ == "__main__":
	main()